const app = getApp();
const baseUrl = 'https://www.platform.tenyuanda.com:1443';
var request = function({
	url,
	data = {},
	method = "GET",
	isFormData = false
}) {
	return new Promise((resolve, reject) => {
		goRequest(url, resolve, reject, data, method, isFormData)
	})
}
var goRequest = function(url, resolve, reject, data = {}, method = "GET", isFormData = false) {
	wx.request({
		url: baseUrl + url,
		data: data,
		method: method,
		header: {
			'content-type': isFormData ? 'application/x-www-form-urlencoded' :
				'application/json; charset=utf-8',
			'Accept': 'application/json',
			'token': wx.getStorageSync('token'),
			'appId': 'wxf0bd7519c93de943'
		},
		success: function(res) {
			var code = res.data.code;
			uni.hideLoading();
			if (code === 401) {
				// 登录态失效, 重新登录
				wx.hideNavigationBarLoading();
				doLogin();
			} else if (code === 403) {
				reject(res.data)
				showError(res.data.msg)
			} else if (code === 0) {
				resolve(res.data);
			} else {
				reject(res.data)
				showError(res.data.msg)
			}
		},
		fail: function(err) {
			console.log(err)
			reject()
			showError(err.errMsg)
		}
	});
}
const doLogin = () => {
	uni.reLaunch({
	  url: "/pages/login/login"
	},10);
	// 保存当前页面
	// let pages = getCurrentPages();
	// if (pages.length) {
	//   let currentPage = pages[pages.length - 1];
	//   "pages/login/login" != currentPage.route &&
	//     wx.setStorageSync("currentPage", currentPage);
	// }
	// 跳转授权页面





	// if (!uni.getStorageSync('noLogin')) {
	// 	uni.navigateTo({
	// 		url: "/pages/login/third_login"
	// 	}, 10);
	// } else {
	// 	uni.reLaunch({
	// 		url: "/pages/login/login"
	// 	}, 10);
	// }
}
/**
 * 显示失败提示框
 */
const showError = (msg, callback) => {
	uni.hideLoading();
	setTimeout(()=>{
		uni.showToast({
			title: msg,
			icon: 'none',
			duration:4000
		});
	},800);
	
	// wx.showModal({
	//   title: '友情提示',
	//   content: msg,
	//   showCancel: false,
	//   success(res) {
	// callback && (setTimeout(() => {
	//   callback();
	// }, 1500));
	//     callback && callback();
	//   }
	// });
}
module.exports = {
	request,
	baseUrl
}